﻿using EventBus;
using LiteStep.Currencies;
using LiteStep.Events;
using LiteStep.Exchanges.BtcE;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LiteStep.Utils.Recorders.BtcE
{
	public class BtcETickerRecorder<TFrom, TTo> : ITickerRecorder<Ticker<TFrom, TTo>>
		where TFrom : ICurrency<TFrom>, new()
		where TTo : ICurrency<TTo>, new()
	{
		protected IEventBus eventBus { get; set; }
		private IHandlerRegistration registration { get; set; }

		public BtcETickerRecorder(IEventBus eventBus)
		{
			this.eventBus = eventBus;
		}

		public void Register()
		{
			if (registration == null)
			{
				registration = eventBus.AddHandler(AfterTickerResponseEvent<Ticker<TFrom, TTo>>.TYPE, this);
			}
		}

		public void Unregister()
		{
			if (registration != null)
			{
				registration.RemoveHandler();
				registration = null;
			}
		}

		public void OnAfterTickerResponseEvent(AfterTickerResponseEvent<Ticker<TFrom, TTo>> e)
		{
			if (e == null || e.Ticker == null)
			{
				LiteStep.Log.ErrorFormat("The BtcE {0}/{1} ticker was not received", typeof(TFrom).Name.ToUpper(), typeof(TTo).Name.ToUpper());
				return; 
			}

			try
			{
				using (var liteStepContext = LiteStep.Ninjector.Get<LiteStepContext>())
				{
					var ticker = new BtcETicker();
					ticker.Base = (int)Enum.Parse(typeof(Currencies.Currencies), typeof(TFrom).Name);
					ticker.Alt = (int)Enum.Parse(typeof(Currencies.Currencies), typeof(TTo).Name);
					ticker.High = (decimal)e.Ticker.High;
                    ticker.Low = (decimal)e.Ticker.Low;
                    ticker.Average = (decimal)e.Ticker.Average;
                    ticker.Volume = (decimal)e.Ticker.Volume;
                    ticker.CurrentVolume = (decimal)e.Ticker.CurrentVolume;
                    ticker.Last = (decimal)e.Ticker.Last;
                    ticker.Buy = (decimal)e.Ticker.Buy;
                    ticker.Sell = (decimal)e.Ticker.Sell;
					ticker.Version = 1;
                    ticker.Timestamp = e.Ticker.Timestamp;
					ticker.InsertedOn = DateTime.Now;

					liteStepContext.BtcETickers.Add(ticker);
					liteStepContext.SaveChanges();
				}
			}
			catch (Exception ex)
			{
				LiteStep.Log.Error(String.Format("There was an error saving the BtcE {0}/{1} ticker", typeof(TFrom).Name.ToUpper(), typeof(TTo).Name.ToUpper()), ex);
			}
			
		}
	}
}
